//
//  DDRefresh.swift
//  SinaMicroBlogSwift2
//
//  Created by dqw on 15/8/4.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit

let kRefreshMargin: CGFloat = -60

class DDRefresh: UIRefreshControl {
    
    override init() {
        super.init()
        
        configurRefreshVC()
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func configurRefreshVC() {
        
        tintColor = UIColor.clearColor()
        
        
        addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
        
        addSubview(refreshView)
        // FIXME: 此处的size是一定要设置的。
        refreshView.ff_AlignInner(type: ff_AlignType.CenterCenter, referView: self, size: refreshView.bounds.size)  
    }
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        let value = frame.origin.y
        
        if value > 0 {
            return
        }
        
        // 拉到一定程度，自动激活刷新。
        if refreshing {
            refreshView.statrtLoading()
        }
        // 里面属性的set方法间接的调用方法。
        if value < kRefreshMargin && !refreshView.rotateFlag {
            refreshView.rotateFlag = true

        }else if value > kRefreshMargin && refreshView.rotateFlag {
            refreshView.rotateFlag = false
        }
    }
    
    override func endRefreshing() {
        super.endRefreshing()
         refreshView.stopLoading()
    }
    // 懒加载的，但是其已经具有size了。
    private lazy var refreshView = DDRefreshView.refreshView()
    deinit {
            removeObserver(self, forKeyPath: "frame")
    }
}
class DDRefreshView : UIView {
    var rotateFlag: Bool = false {
        didSet {
            rotatePullIcon()
        }
    }
    @IBOutlet weak var loadView: UIView!
    @IBOutlet weak var pullIcon: UIImageView!
    @IBOutlet weak var loadIcon: UIImageView!

    private func rotatePullIcon() {
        
        // FIXME: transform的旋转动画在闭包里面遵守最近原则。
        let angle = rotateFlag ? M_PI - 0.01 : M_PI + 0.01
        
        UIView.animateWithDuration(1.0) { () -> Void in
            
            self.pullIcon.transform = CGAffineTransformRotate(self.pullIcon.transform, CGFloat(angle))
        }
    }
    
    private func statrtLoading() {
        loadView.hidden = false
        // FIXME: 防止重复添加动画。
        if loadIcon.layer.animationForKey("loadIcon") != nil {
            return
        }
        let ani = CABasicAnimation(keyPath: "transform.rotation")
        
        ani.toValue = 2 * M_PI
        ani.repeatCount = MAXFLOAT
        ani.repeatDuration = 10.0
        
        loadIcon.layer.addAnimation(ani, forKey: "loadIcon")
  
    }
    // 动画也要在结束时移除。
    private func stopLoading() {
        loadView.hidden = true
        loadIcon.layer.removeAllAnimations()
    }
    // 没有放在init方法里面，不知道有什么讲究。
    class func refreshView() -> DDRefreshView {
        return NSBundle.mainBundle().loadNibNamed("DDRefreshView", owner: nil, options: nil).last as! DDRefreshView
    }

   
}


